<?php
  /**
   * This is the Template Parser Engine, all logic for parsing is done in this class
   *
   * @author Macdonald Terrence Robinson
   * @package Core
   *
   */
  final class Parser
  {
    private static $startTag = '{';
    private static $endTag = '}';
    private static $variables = array();

    public static function init()
    {
      self::$variables = get_class_vars('Config');

      self::$variables['currentURL'] = URI::getURL(true);
      self::$variables['currentController'] = Router::$controller;
      self::$variables['currentFunction'] = Router::$function;
      self::$variables['queryString'] = URI::getQueryString();

      if( Config::$appendIndexPhpToURL )
        self::$variables['siteURL'] = self::$variables['siteURL'].'index.php/';

      self::$variables = array_merge(self::$variables, Config::$customConfigs );
    }

    public static function initCurrentNodeAttributes()
    {
      $attrubutes = SiteMap::getAllAttrsByLanguage();
      self::$variables = array_merge(self::$variables, $attrubutes);
    }

    public static function compileAndParse($filePath, $customVariables = array(), $parseSnippets = true)
    {      
      $data = self::compile($filePath, $customVariables);
      $data = self::parseData($data, $customVariables, $parseSnippets);

      return $data;
    }
    
    public static function parseData($data, array $customVariables = array(), $parseSnippets = false)
    {
      if( $data == '' || trim($data) == '')
        return '';
      
      //xdebug_dump_function_profile(4);
      if( strstr($data, '://' ) )
      {
        $data = str_replace('https://', 'http://', $data);
        $data = str_replace('http://', Config::$protocol.'://', $data);
      }

      if( strstr($data, self::$startTag) )
      {
        $variables = self::getAllVariables($customVariables);

        $templateTags = array();
        $templateValues = array();

        foreach ($variables as $key=>$value)
        {
          if( !is_string($value) )
            continue;

          $templateTags[] = self::$startTag.$key.self::$endTag;
          $templateValues[] = $value;
        }

        $data =  str_replace($templateTags, $templateValues , $data);

        /*$pattern = '/[{]+(POST_[a-zA-Z0-9]{1,}|GET_[a-zA-Z0-9]{1,}|SESSION_[a-zA-Z0-9]{1,})[}]+/i';
        $data = preg_replace($pattern, '', $data);*/

        if($parseSnippets)
        {
          $data = preg_replace_callback(
                '/[{]{1}[a-z?=\s,\w\d&;|<>\/\"\'"`]+[}]{1}/i',
                array('Parser', 'parseSnippets'),
                $data);
        }
      }
      
      return $data;
    }

    protected static function parseSnippets($matches)
    {
      $snippetCall = str_replace(array('{','}','amp;'), '', $matches[0]);
      $segments = explode('?', $snippetCall);

      $function = trim($segments[0]);
      $paramString = '';

      if( count($segments) > 1 )
        $paramString = $segments[1];

      $path = Config::$siteDir.Config::$snippetsDir.$function.'/'.$function.'.php';

      if(!file_exists($path))
        return $matches[0];
      
      if(!class_exists($function))
          require $path;

      Master::initFunction($function, 'init', Master::getCurrentController() );
      
      $params = explode('&', $paramString);
      
      $args = array();
      foreach($params as $key=>$value)
      {
        $value = trim($value);
        
        if( !stristr($value, '=`'))
          continue;        
        
        list($keyName, $keyValue) = explode('=`', $value);
        
        $keyValue = str_replace('`', '', $keyValue);
        $args[trim($keyName)] = trim($keyValue);
      }

      return Master::initFunction($function, 'start', $args);
    }

    public static function getConfigVariablesByLimit(array $limitToVariables)
    {
      $variables = self::getAllVariables();      
      $newVars = array();
      
      foreach ($limitToVariables as $limitToVariable)
      {
      	if( ( isset($variables[$limitToVariable]) ) && (is_string($variables[$limitToVariable])) )
          $newVars[$limitToVariable] = $variables[$limitToVariable];
      }

      return $newVars;
    }
    
    private static function convertToTemplateVariable($variable)
    {
      return self::$startTag.$variable.self::$endTag;
    }

    public static function replaceWithTemplateVariables($newContent)
    {
      $newContent = str_replace('https://', 'http://', $newContent);
      $newContent = str_replace('http://', Config::$protocol.'://', $newContent);

      $templateVariables = self::getConfigVariablesByLimit( array('siteURL', 'siteDir', 'siteName', 'protocol') );

      $siteURL = $templateVariables['siteURL'];
      $siteURL = str_replace('index.php/', '', $siteURL);
      
      $templateVariables['siteURL'] = $siteURL;
      $newContent = str_replace($siteURL.'index.php/', $siteURL, $newContent);

      foreach ($templateVariables as $key=>$value)
        $newContent = str_replace($value, self::convertToTemplateVariable($key), $newContent);

      return $newContent;
    }

    public static function getAllVariables(array $customVariables = array())
    {      
      if( count($customVariables) > 0 )
        return array_merge(self::$variables, $customVariables);
      else
        return self::$variables;
    }
    
    public static function compile($filePath, $customVariables = array())
    {
      $variables = self::getAllVariables($customVariables);

      ob_start();
      extract((array) $variables);
      
      if(is_file($filePath))
        include $filePath;
        
      $data = ob_get_clean();
      //xdebug_dump_function_profile(4);
      
      return $data;

    }
    
  }
  
?>
